<template>
  <!-- 党员管理 -->
  <base-breadcrumb :title="$route.meta.title">
    <a-row :gutter="10" class="page-height">
      <!-- 树搜索 -->
      <a-col :span="6">
        <a-card class="page-height-tree">
          <!-- <title-name title="党组织架构" /> -->
          <!-- 党组织树搜索 -->
          <!-- :expandByAuto="true" -->
          <TreePartyOrg ref="treeOrganization" :datas="treeDataList" :default-selected-keys="defKeys"
            :selected-keys.sync="selectedKeys" :select-options.sync="selectOptions" :show-child-with-search="true"
            :org-status="1" @loader="getTable" />
        </a-card>
      </a-col>
      <a-col :span="18" class="page-height-list-wrapper">
        <!-- 搜索 -->
        <searchData class="party-search" :search-data="searchArr" @search="search" :labelCol="{ span: 14 }"
          :wrapperCol="{ span: 10 }" :rowCount="2" />
        <!-- 表格 -->

        <a-card :bordered="false" class="page-height-list">
          <title-name title="党员信息列表" />
          <a-button v-btnPermission="'pa_005_add_01'" class="mb12" type="primary" icon="plus"
            :disabled="selectedKeys.length == 0 || selectOptions.orgType !== 3" @click="showAddMemberModal('add')">
            新增党员
          </a-button>
          <excel ref="exportBtn" v-btnPermission="'pa_005_exp_02'" file-name="党费收缴记录模板" is-click-generate="false">
            <a-button slot="excelBtn" type="primary" icon="export" class="mb12" :loading="loadingState.isExport"
              @click="handleExport">
              党费收缴模板下载
            </a-button>
          </excel>
          <!-- <export-mould v-btnPermission="'pa_005_exp_02'" class="mb12" buttonText="导出模板（党费收缴记录）" templateCode="党费收缴记录模板.xlsx" icon="cloud-download"></export-mould> -->
          <ExcelImportButton v-btnPermission="'pa_005_imp_03'" class="mb12" icon="import"
            :loading="loadingState.isImport" :disabled="selectedKeys.length == 0 || selectOptions.orgType !== 3"
            :button-text="'党费收缴导入'" @handleSubmit="handleImport" />
          <excel ref="exportBtnTwo" v-btnPermission="'pa_005_exp_02'" file-name="党员信息列表" is-click-generate="false">
            <a-button slot="excelBtn" type="primary" icon="cloud-upload" class="mb12"
              :loading="loadingState.isExportTwo" @click="handleExportList">
              导出党员
            </a-button>
          </excel>
          <ExportExcel ref="exportExcel" class="mr20" :export-list="exportList" file-name="党员列表模板.xlsx"
            button-text="党员批量导入模板下载" />
          <ExcelImportButton v-btnPermission="'pa_005_imp_03'" class="mb12" icon="import"
            :loading="loadingState.isImportTwo" :button-text="'党员批量导入'" @handleSubmit="handleImportMembers" />
          <div class="pub-table-select-count" style="margin: 10px 0">
            <a-icon type="info-circle" theme="twoTone" />
            <span>
              共计：
              <a>{{ statisticsInfo.totalNum || 0 }} 个</a>
            </span>
          </div>
          <!-- 表格 -->
          <!-- tableLayout="fixed" -->
          <list-table ref="table" size="default" row-key="id" :columns="columns" :request="loadData" :alert="true"
            show-size-changer show-quick-jumper show-pagination="auto">
            <span slot="type" slot-scope="text">
              {{ text == 1 ? '正式党员' : '预备党员' }}
            </span>
            <span slot="status" slot-scope="text">
              {{ text == 2 ? '对内转出中' : '正常' }}
            </span>
            <template slot="actions" slot-scope="text, record">
              <MoreButton>
                <a v-btnPermission="'pa_005_add_01'" @click="handleManage('look', record)">查看</a>
                <a v-btnPermission="'pa_005_edi_05'" @click="handleManage('edit', record)">编辑</a>
                <span v-if="record.status == 1" v-btnPermission="'pa_005_shi_06'">
                  <a @click="showInwardTransferModal(record, 'turnIn')">组织关系转接</a>
                </span>
                <span v-if="record.status == 1" v-btnPermission="'pa_005_rol_06'">
                  <a @click="showInwardTransferModal(record, 'turnOut')">对外转出</a>
                </span>
                <span v-if="record.approvalButton == 1" v-btnPermission="'pa_005_moi_07'">
                  <approval-button :id="record.id" text="审批信息" />
                </span>
              </MoreButton>
            </template>
          </list-table>
        </a-card>
      </a-col>
    </a-row>

    <Transfer :visible.sync="inwardTransferModal.visible" :init-data="inwardTransferModal.childInitData"
      :modal-type="inwardTransferModal.type" @ok="getTable" />

    <AddMember :visible.sync="addMemberModalVisible" :cur-option="selectOptions" @submitSuccess="getTable" />
  </base-breadcrumb>
</template>

<script>
import moment from 'moment'
import { STable } from '@/components' // 表格
import Selector from '@/components/Select/Selector'
import BasePage from '@/views/basePage' // 基础配置
import TreePartyOrg from '@/components/businessComponents/TreePartyOrg' // 树
// import ExportMould from '@/components/ExportMould' // 导出模板文件按钮
import ExportExcel from '@/components/exportExcel/ExportExcel'

import OrgTypeSelect from '../componments/orgTypeSelect.vue'
import Transfer from './transfer.vue'
import AddMember from './addMember.vue'
import TurnInMember from '../partyManage/flexMemberInfo/TurnInMember.vue'
import { getPagePartyMember, cancelByPrimaryKey, importPartyFeeRecords, batchAddPartyMember } from '@/api/partyMasses'
const searchArr = [
  // 搜索框
  {
    name: '名称/党支部名称/手机号码/员工编号',
    type: 'input',
    value: 'conditions',
  },
  {
    name: '状态',
    value: 'status',
    type: 'select',
    data: [
      { value: '2', label: '对内转出中' },
      { value: '1', label: '正常' }
    ]
  }
]
const columns = [
  {
    title: '序号',
    width: 60,
    dataIndex: 'index',
    customRender() {
      return arguments[2] + 1
    }
  },
  {
    title: '党员名称',
    width: '150px',
    dataIndex: 'userName'
  },
  {
    title: '党支部名称',
    width: '300px',
    dataIndex: 'partyOrgName'
  },
  {
    title: '党员类型',
    dataIndex: 'type',
    width: '100px',
    scopedSlots: { customRender: 'type' }
  },
  {
    title: '确定预备党员时间',
    width: '150px',
    dataIndex: 'proPartyTime'
  },
  {
    title: '预备转正时间',
    width: '120px',
    dataIndex: 'positiveTime'
  },
  {
    title: '员工编号',
    width: '110px',
    dataIndex: 'employeeNum'
  },
  {
    title: '手机号码',
    width: '120px',
    dataIndex: 'phone'
  },
  {
    title: '党内职务',
    width: '200px',
    dataIndex: 'partyPost'
  },
  {
    title: '当前岗位',
    width: '200px',
    dataIndex: 'currentPost'
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: '90px',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'actions',
    width: '120px',
    fixed: 'right',
    // align: 'center',
    scopedSlots: { customRender: 'actions' }
  }
]
export default {
  name: 'a' + Date.now(),
  extends: new BasePage(),
  components: {
    AddMember,
    STable,
    TreePartyOrg,
    // OrgTypeSelect,
    Transfer,
    ExportExcel
    // ExportMould
  },
  data() {
    this.columns = columns
    this.searchArr = searchArr
    return {
      loadingState: {
        isImport: false,
        isImportTwo: false,
        isExport: false,
        isExportTwo: false
      },
      queryParam: {}, // 查询参数
      treeDataList: [],
      defOptions: {},
      defKeys: [],
      selectOptions: {}, // 选中节点对象
      selectedKeys: [],
      statisticsInfo: {
        totalNum: 0
      },
      inwardTransferModal: {
        visible: false,
        childInitData: {},
        type: 'turnIn',
        curId: null,
        curName: null
      },
      addMemberModalVisible: false,
      addMemberForm: {
        personIds: []
      },
      addModalVisible: false,
      exportList: [
        {
          columns: [
            {
              width: 100,
              title: '党员名称',
              dataIndex: 'userName'
            },
            {
              width: 100,
              title: '党支部名称',
              dataIndex: 'partyOrgName'
            },
            {
              width: 150,
              title: '党员类型',
              dataIndex: 'type',
              options: ['正式党员', '预备党员'],
              excelConfig: {
                dataValidation: {
                  type: 'list'
                }
              }
            },
            {
              width: 150,
              title: '确定预备党员时间',
              dataIndex: 'proPartyTime',
              excelConfig: {
                note: '时间格式为：YYYY/MM/DD 如2020/2/2'
              }
            },
            {
              width: 150,
              title: '预备转正时间',
              dataIndex: 'positiveTime',
              excelConfig: {
                note: '时间格式为：YYYY/MM/DD 如2020/2/2'
              }
            },
            {
              width: 150,
              title: '手机号码',
              dataIndex: 'phone'
            }
          ],
          datas: [
            {
              userName: '张三（示例）',
              partyOrgName: '中建八局西南公司四川分公司机关支部委员会（示例）'
            }
          ]
        }
      ],
      loadData: (parameter) => {
        const query = {
          partyOrgId: this.selectedKeys.length ? this.selectedKeys[0] : '',
          ...this.queryParam
        }
        const requestParameters = Object.assign({}, parameter, { query: query })
        return getPagePartyMember(requestParameters).then((res) => {
          const obj = {
            code: 200,
            data: res.data.list || [],
            totalSize: res.data.total,
            currentPage: res.data.pageNum
          }
          this.statisticsInfo.totalNum = res.data.total
          return obj
        })
      }, // 加载数据方法 必须为 Promise 对象

      form: {}
    }
  },
  mounted() {
    this.refresh()
  },
  methods: {
    refresh() {
      this.$refs.treeOrganization.getList().then((res) => {
        const def = this.treeDataList.find((item) => {
          return !item.disabled
        })
        this.defOptions = def
        this.selectOptions = def
        this.selectedKeys = def ? [def.id] : []
        this.defKeys = def ? [def.id] : []
        this.$refs.table.refresh()
      })
    },
    // 搜索
    search(value) {
      const params = { ...value }
      if (params) {
        this.queryParam = {
          ...params
        }
      }
      this.$refs.table.refresh()
    },
    getTable(value) {
      this.$refs.table.refresh()
    },
    showAddMemberModal() {
      this.addMemberModalVisible = true
    },
    showInwardTransferModal(data, pageType) {
      this.inwardTransferModal.childInitData = {
        id: data.id,
        partyMemberName: data.userName
      }
      this.inwardTransferModal.visible = true
      this.inwardTransferModal.type = pageType
    },
    // 操作栏
    handleManage(type, record, addpersion = 'false') {
      if (type == 'look') {
        this.$router.push({
          name: 'PartyMassesPartyMemberDetail',
          query: {
            id: record.id || '',
            type: type
          }
        })
      } else if (type == 'edit') {
        this.$router.push({
          name: 'PartyMassesPartyMemberEdit',
          query: {
            id: record.id || '',
            type: type
          }
        })
      }
    },
    /**
     * 导入
     */
    async handleImport(list) {
      try {
        if (this.loadingState.isImport) return
        // this.loadingState.isImport = true
        // 读取到的日期时间会被解析会数字，因此这里将其转换回YYYY-MM-DD格式
        const formatDate = (numb, format) => {
          const time = new Date((numb - 1) * 24 * 3600000 + 1)
          time.setYear(time.getFullYear() - 70)
          const year = time.getFullYear() + ''
          const month = time.getMonth() + 1 + ''
          const date = time.getDate() - 1 + ''
          if (format && format.length === 1) {
            return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
          }
          return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
        }
        const deadline = (date) => {
          let nowdate = new Date(date)
          nowdate.setMonth(nowdate.getMonth() + 1)
          return moment(new Date(nowdate)).format('YYYY年MM月') //this.$dateFormat(new Date(nowdate), 'M')
        }
        // 党支部名称、姓名、党费缴纳基数、党费缴纳额度、具体起始时间、具体截止时间
        const columns = [
          { title: '党支部名称', dataIndex: 'partyOrgName' },
          { title: '姓名', dataIndex: 'userName' },
          { title: '党费缴纳基数', dataIndex: 'payBase' },
          { title: '党费缴纳额度', dataIndex: 'payLimit' },
          { title: '具体起始时间', dataIndex: 'startTime' },
          { title: '具体截止时间', dataIndex: 'endTime' }
        ]
        const paramsList = []
        list &&
          list.forEach((item) => {
            const resultItem = {}
            for (const key in item) {
              const target = columns.find((column) => column.title === key)
              if (target) {
                if (target.title === '具体起始时间' || target.title === '具体截止时间') {
                  if (typeof item[key] == 'number') {
                    resultItem[target.dataIndex] = formatDate(item[key], '-')
                  } else if (typeof item[key] == 'object') {
                    if (!new Date(item[key]) instanceof Date || isNaN(new Date(item[key]).getTime())) {
                      this.loadingState.isImport = false
                      this.$message.warning(`${target.title}填写有误`)
                      return
                    }
                    const date = item[key].setDate(item[key].getDate() - 1)
                    resultItem[target.dataIndex] = moment(new Date(date)).format('YYYY-MM-DD')
                  } else {
                    if (!new Date(item[key]) instanceof Date || isNaN(new Date(item[key]).getTime())) {
                      this.loadingState.isImport = false
                      this.$message.warning(`${target.title}填写有误`)
                      return
                    }
                    resultItem[target.dataIndex] = moment(new Date(item[key])).format('YYYY-MM-DD')
                  }
                  // resultItem[target.dataIndex] = typeof item[key] == 'number' ? formatDate(item[key], '-') : moment(new Date(item[key])).format('YYYY-MM-DD');
                } else {
                  resultItem[target.dataIndex] = item[key]
                }
              }
            }
            if (resultItem['endTime']) resultItem.deadline = deadline(resultItem['endTime'])
            resultItem.partyOrgId = this.selectOptions.id
            paramsList.push(resultItem)
          })
        if (!paramsList.length) {
          this.$message.warning('请录入导入数据')
          this.loadingState.isImport = false
          return
        }
        const res = await importPartyFeeRecords(paramsList)
        this.loadingState.isImport = false
        if ((res && res.code == 0) || (res && res.data && res.data.code == 0)) {
          const msg = res.msg || res.data.msg
          this.$message.success(msg)
          this.$refs.table.refresh(true)
        } else {
          this.$message.error('导入失败！')
        }
      } catch (e) {
        console.error(e)
        this.loadingState.isImport = false
      }
    },
    /**
     * 导入党员
     */
    async handleImportMembers(list) {
      try {
        this.loadingState.isImportTwo = true
        // 读取到的日期时间会被解析会数字，因此这里将其转换回YYYY-MM-DD格式
        const formatDate = (numb, format) => {
          const time = new Date((numb - 1) * 24 * 3600000 + 1)
          time.setYear(time.getFullYear() - 70)
          const year = time.getFullYear() + ''
          const month = time.getMonth() + 1 + ''
          const date = time.getDate() - 1 + ''
          if (format && format.length === 1) {
            return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
          }
          return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
        }

        // 党支部名称、姓名、党费缴纳基数、党费缴纳额度、具体起始时间、具体截止时间
        const columns = [
          { title: '党支部名称', dataIndex: 'partyOrgName' },
          { title: '党员名称', dataIndex: 'userName' },
          { title: '党员类型', dataIndex: 'type' },
          { title: '手机号码', dataIndex: 'phone' },
          { title: '确定预备党员时间', dataIndex: 'proPartyTime' },
          { title: '预备转正时间', dataIndex: 'positiveTime' }
        ]
        const paramsList = []
        for (const item of list) {
          const resultItem = {}
          for (const key in item) {
            const target = columns.find((column) => column.title === key)
            if (target?.title === '确定预备党员时间' || target?.title === '预备转正时间') {
              if (typeof item[key] == 'number') {
                resultItem[target.dataIndex] = formatDate(item[key], '-')
              } else if (typeof item[key] == 'object') {
                if (!new Date(item[key]) instanceof Date || isNaN(new Date(item[key]).getTime())) {
                  this.loadingState.isImportTwo = false
                  this.$message.warning(`${target.title}填写有误`)
                  return
                }
                const date = item[key].setDate(item[key].getDate() - 1)
                resultItem[target.dataIndex] = moment(new Date(date)).format('YYYY-MM-DD')
              } else {
                if (!new Date(item[key]) instanceof Date || isNaN(new Date(item[key]).getTime())) {
                  this.loadingState.isImportTwo = false
                  this.$message.warning(`${target.title}填写有误`)
                  return
                }
                resultItem[target.dataIndex] = moment(new Date(item[key])).format('YYYY-MM-DD')
              }
              // resultItem[target.dataIndex] = typeof item[key] == 'number' ? formatDate(item[key], '-') : moment(new Date(item[key])).format('YYYY-MM-DD');
            } else if (target.title === '党员类型') {
              resultItem[target.dataIndex] = { 正式党员: 1, 预备党员: 2 }[item[key]]
            } else {
              resultItem[target.dataIndex] = item[key]
            }
          }
          paramsList.push(resultItem)
        }
        if (!paramsList.length) {
          this.$message.warning('请录入导入数据')
          this.loadingState.isImportTwo = false
          return
        }
        const res = await batchAddPartyMember(paramsList)
        this.loadingState.isImportTwo = false
        if ((res && res.code == 0) || (res && res.data && res.data.code == 0)) {
          this.$message.success('导入成功！')
          this.$refs.table.refresh(true)
        } else {
          this.$message.error('导入失败！')
        }
      } catch (e) {
        console.error(e)
        this.loadingState.isImportTwo = false
      }
    },
    /**
     * @description:导出党员
     */
    handleExportList() {
      const query = {
        partyOrgId: this.selectedKeys.length ? this.selectedKeys[0] : '',
        ...this.queryParam
      }
      const requestParameters = Object.assign({}, { needCount: false }, { query: query })
      this.loadingState.isExportTwo = true
      getPagePartyMember(requestParameters)
        .then((res) => {
          this.loadingState.isExportTwo = false
          if (res && res.code == 0) {
            if (res.data.list?.length > 0) {
              res.data.list?.forEach((item, index) => {
                item.index = (index + 1).toString()
                item.type = item.type == 1 ? '正式党员' : '预备党员'
                item.status = item.status == 2 ? '对内转出中' : '正常'
              })
              const list = res.data.list
              const columns = this.columns.concat()
              columns.splice(2, 0, {
                title: '党总支名称',
                dataIndex: 'partyPOrgName',
              })
              this.$refs.exportBtnTwo.generateExcel(list, { columns: columns }, 0)
            } else {
              this.$message.warning('没有数据可导出！')
            }
          }
        })
        .catch(() => {
          this.loadingState.isExportTwo = false
        })
    },
    handleExport() {
      try {
        if (this.loadingState.isExport) return
        this.loadingState.isExport = true
        const query = {
          partyOrgId: this.selectedKeys.length ? this.selectedKeys[0] : '',
          ...this.queryParam
        }
        const params = {
          needCount: false,
          query: query
        }
        // 党支部名称、姓名、党费缴纳基数、党费缴纳额度、具体起始时间、具体截止时间
        const columns = [
          { title: '党支部名称', dataIndex: 'partyOrgName' },
          { title: '姓名', dataIndex: 'userName' },
          { title: '党费缴纳基数', dataIndex: 'payBase' },
          { title: '党费缴纳额度', dataIndex: 'payLimit' },
          { title: '具体起始时间', dataIndex: 'startTime' },
          { title: '具体截止时间', dataIndex: 'endTime' }
        ]
        getPagePartyMember(params)
          .then((res) => {
            this.loadingState.isExport = false
            if (res && res.code == 0) {
              if (res.data.list?.length > 0) {
                const list = res.data.list.map((item, index) => {
                  return {
                    partyOrgName: item.partyOrgName,
                    userName: item.userName
                  }
                })
                this.$refs.exportBtn.generateExcel(list, { columns }, 0)
              }
            } else {
              this.$message.warning('没有数据可导出！')
            }
          })
          .catch(() => {
            this.loadingState.isExport = false
          })
      } catch (e) {
        console.error(e)
        this.loadingState.isExport = false
      }
    }
  }
}
</script>
<style lang="less" scoped>
// .party-search {
//   /deep/ .ant-form-item .ant-form-item-label {
//     width: 142px;
//   }
// }
.mb12 {
  margin-right: 10px;
}
</style>
